package com.xhtranslate.service.baidu.serviceImpl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhtranslate.common.config.TranslateConfig;
import com.xhtranslate.common.dto.ImageFormDTO;
import com.xhtranslate.common.dto.TextFormDTO;
import com.xhtranslate.common.util.AddUseLimitThreadUtil;
import com.xhtranslate.common.util.HttpGetPostUtil;
import com.xhtranslate.common.util.JudgeCreditLimitUtil;
import com.xhtranslate.common.util.MD5;
import com.xhtranslate.common.vo.ResponseEnum;
import com.xhtranslate.service.baidu.service.BaiduOcrService;
import com.xhtranslate.service.baidu.service.BaiduTranslateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author liuxuhuang
 * @version 1.0
 * @package com.xhtranslate.service.baidu.serviceImpl
 * @date 2022/11/2 21:06:51
 * @description
 */
@Service
@Slf4j
public class BaiduTranslateImpl implements BaiduTranslateService {
    @Autowired
    private HttpGetPostUtil requestUtil;
    @Autowired
    private BaiduOcrService baiduOcrService;
    @Autowired
    private JudgeCreditLimitUtil judgeCreditLimitUtil;
    @Autowired
    private AddUseLimitThreadUtil addUseLimitThreadUtil;
    /**
     * 特殊字符匹配
     */
    private Pattern stringPattern = Pattern.compile(TranslateConfig.SpecialString);

    @Override
    public StringBuffer commonTranslate(TextFormDTO dto) {
        StringBuffer textString = new StringBuffer(dto.getContext());
        String string = textString.toString();
        textString.delete(0, textString.length());
        if (!string.contains("\n")) {
            textString = startTranslate(string, dto.getFrom(), dto.getTo());
        } else {
            String[] split = string.split("\n");
            for (int i = 0; i < split.length; i++) {
                if (StringUtils.isNotBlank(split[i]) && !Objects.isNull(split[i])) {
                    textString.append(startTranslate(split[i], dto.getFrom(), dto.getTo()) + "\n");
                } else {
                    textString.append("\n");
                }
            }
        }
        log.info("百度文本翻译后==>内容==>" + textString);
        return textString;
    }

    public StringBuffer startTranslate(String string, String from, String to) {
        Matcher matcher = stringPattern.matcher(string);
        string = matcher.replaceAll(" ");
        StringBuffer buffer = new StringBuffer();
        log.info("百度文本翻译前=>内容=>" + string);
        long salt = System.currentTimeMillis();
        String str = TranslateConfig.BaiduAppId + string +
                salt + TranslateConfig.BaiduSecreKey;
        String sign = MD5.md5(str);
        String url = TranslateConfig.BaiduRequestUrl + "?q=" + string + "&from=" + from + "&to=" + to
                + "&appid=" + TranslateConfig.BaiduAppId + "&salt=" + salt + "&sign=" + sign;
        JSONObject jsonObject = requestUtil.httpPost(url, JSONObject.class);
        if (!jsonObject.toString().contains("error_msg")) {
            JSONArray jsonArray = jsonObject.getJSONArray("trans_result");
            for (int i = 0; i < jsonArray.size(); i++) {
                buffer.append(jsonArray.getJSONObject(i).getString("dst")).append("\n");
            }
        }
        addUseLimitThreadUtil.addCreditLimit(TranslateConfig.BaiduTextTranslateRedisName, buffer.length());
        return buffer;
    }

    @Override
    public StringBuffer imageTranslate(ImageFormDTO dto) throws IOException {
        String ocrImgString = baiduOcrService.ocrImg(dto.getFile());
        log.info("百度图片翻译前：" + ocrImgString);
        boolean b = judgeCreditLimitUtil.getBeyondTextCredit(TranslateConfig.BaiduTextTranslateRedisName, TranslateConfig.BaiduTextTranslateRedisCreditLimit, ocrImgString.length());
        if (!b) {
            return new StringBuffer(ResponseEnum.OVERCREDITLIMIT.getMsg());
        }
        TextFormDTO textFormDTO = new TextFormDTO(dto.getPlatform(), dto.getFrom(), dto.getTo(), ocrImgString);
        StringBuffer translateText = commonTranslate(textFormDTO);
        log.info("百度图片翻译后：" + translateText);
        return translateText;
    }

    public JSONObject packingParams(File file, String from, String to, String salt, String sign) {
        JSONObject object = new JSONObject();
        object.put("image", file);
        object.put("from", from);
        object.put("to", to);
        object.put("appid", TranslateConfig.BaiduAppId);
        object.put("salt", salt);
        object.put("cuid", "APICUID");
        object.put("mac", "mac");
        object.put("version", "3");
        object.put("sign", sign);
        return object;
    }
}
